<template>
	<section>
		<!--高级查询工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="changePage">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--部门列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column type="index" label="序号" width="40"></el-table-column>
			<el-table-column prop="sn" label="部门描述" width="120" sortable></el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable></el-table-column>
			<el-table-column prop="dirPath" label="部门路劲" width="120" sortable></el-table-column>
			<el-table-column prop="state" label="部门状态" width="120"sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state===0">启用</span>
					<span style="color: red" v-else-if="scope.row.state===-1">禁用</span>
					<span style="color: blue" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" width="120" sortable></el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="150" sortable></el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size=pageSize :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
				<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
					<el-form-item label="部门编号" prop="sn"><el-input v-model="editForm.sn" auto-complete="off"></el-input></el-form-item>
					<el-form-item label="部门名称" prop="name"><el-input v-model="editForm.name" auto-complete="off"></el-input></el-form-item>
					<el-form-item label="启动状态">
						<el-radio-group v-model="editForm.state">
							<el-radio class="radio" :label="0">启用</el-radio>
							<el-radio class="radio" :label="-1">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="部门经理">
						<!--<el-input v-model="editForm.manager"></el-input>-->
						<el-select v-model="editForm.manager"  value-key="id" placeholder="请选择">
							<el-option
									v-for="emp in employees"
									:label="emp.username"
									:value="emp">
								<span style="float: left">{{ emp.username }}</span>
								<span style="float: right; color: #8492a6; font-size: 13px">{{ emp.phone }}</span>
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="上级部门" prop="parent">
							<!--<el-input v-model="editForm.parent" auto-complete="off"></el-input>-->
							<el-cascader v-model="editForm.parent"
										 :options="parents"
										 :props="{
										  checkStrictly: true,
										  value:'id',
										  label:'name'
									 }"clearable>
							</el-cascader>
					</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<!--<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="addForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="addForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>-->
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
                    keyword: ''
				},
				departments: [],
                employees:[],
                parents:[],
				total:0,
                title:"",
				currentPage: 1,
				pageSize:5,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
					sn: [
						{ required: true, message: '请输入部门描述', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
				    sn:'',
					name:'',
					state:0,
                    manager:{},
                    parent:{}
				},
			}
		},
		methods: {
            handleCurrentChange(val) {
			    //alert(val)
				/*页面改变时候发生的查询*/
				this.currentPage = val;
                this.getDepartments();
			},
			/*高级查询：当查询时把页数设置为1在进行查询*/
            changePage(){
				this.currentPage = 1;
                this.getDepartments();
            },
			//获取部门列表
			getDepartments() {
				let para = {
					currentPage: this.currentPage,
					pageSize: this.pageSize,
                    keyword:this.filters.keyword
				};
				this.$http.post("/dept",para)
					.then(result=>{
                        //console.log("高级查询:",result)
                        result = result.data
                        //console.log(result.count)
						this.total = result.count
                        this.departments=result.data
					}).catch(result=>{
					    alert("操作错误")
				})
			},
			/*获取所有用户*/
			getEmployees(){
			  this.$http.get("/emp")
				  .then(result=>{
				      //console.log(result)
				      this.employees=result.data
				  }).catch(result=>{
				      alert("查询员工错误")
			  })
			},
			/*获取部门及其父类*/
			getParents(){
			    this.$http.get("/dept/tree")
					.then(result=>{
						/*console.log("result:======",result)
						console.log("result.data:===========",result.data)*/
						this.parents = result.data
					}).catch(result=>{

					})
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
				    /*开启模态框*/
					this.listLoading = true;
					//NProgress.start();
					/*发送delete请求到后台*/
                    this.$http.delete("/dept/"+row.id)
                        .then(result=>{
                            /*关闭模态框*/
                            this.listLoading = false;
                            //console.log("单条删除：",result)
							if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
							}else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'success'
                                });
							}
                            this.getDepartments()
                        }).catch(result=>{
                        	alert("系统异常")
                    })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
                /*打开模态框*/
                this.title="编辑"
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
				/*回显*/
                var arr = row.dirPath.split("/");
                arr = arr.slice(1,arr.length-1);/*["2","5"]*/
                /*把字符串遍历成数组*/
                for (var i in arr){
                    arr[i] = parseInt(arr[i])
				}
                //console.log(arr)
				/*把遍历出来的数组给editForm.parent绑定完成部门回显*/
				this.editForm.parent=arr
			},
			//显示新增界面
			handleAdd: function () {
                /*打开模态框*/
				this.editFormVisible = true;
				this.editForm = {
                    sn:'',
                    name: '',
                    state:0,
                    manager:{},
                    parent:{}
				};
                this.title="添加"
			},
			//提交按钮
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							/*拷贝一个对象用于提交*/
							let para = Object.assign({}, this.editForm);
							/*把parent[数组]取出来变成一个等对象，并且只需要取最后一个值即可*/
							var arr = this.editForm.parent/*这是一个数组[2,5]*/
							/*加上一个判断，判断添加部门是个添加了上级部门*/
							if(arr.length != null){//当添加了上级部门的时候
                                /*取出最后一个值变为数组，注意是拷贝的对象中*/
                                para.parent = {"id":arr[arr.length-1]}
							}

							this.$http.put("/dept",para)
								.then(result=>{
								    /*关闭模态框*/
                                    this.editFormVisible = false;
                                    /*关闭忙态框*/
                                    this.editLoading = false;
                                    //console.log("result00000000000000000000000",result)
									if(result.data.success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
									}else {
                                        this.$message({
                                            message: '提交失败',
                                            type: 'success'
                                        });
									}
                                    /*刷新页面数据*/
                                    this.getDepartments()
								}).catch(result=>{
                                	alert("系统错误")
							})


							/*editDepartment(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepartments();
							});*/
						});
					}
				});
			},
			//新增
			/*addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						    /!*开启模态框*!/
							this.addLoading = true;
							//NProgress.start();
							/!*复制一个对象用于向后台传值*!/
							let para = Object.assign({}, this.addForm);
							this.$http.put("/dept",para)




							/!*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');*!/
							/!*addDepartment(para).then((res) => {//成功
								this.addLoading = false;
								this.
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getDepartments();
							});*!/
						});
					}
				});
			},*/
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);

				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					/*获取ids:一个数组*/
					/*let para = { ids: ids };*/
					this.$http.patch("/dept",ids)
						.then(result=>{
						    //关闭忙态框
                            this.listLoading = false;
                            /*ids:一个数组传递给后台*/
						    //console.log("批量删除",ids)
							//console.log("批量删除",result)
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            }else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'success'
                                });
                            }
                            this.getDepartments()
						}).catch(result=>{
                        	alert("系统异常")
						})
				}).catch(() => {

				});
			}
		},
		/*页面加载完成后自动调用的方法*/
		mounted() {
			this.getDepartments();
			this.getEmployees();
			this.getParents();
		}
	}

</script>

<style scoped>

</style>